package com.itheima.servlet04;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;

@WebServlet(name = "studentServlet04")
public class StudentServlet04 extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String username = request.getParameter("username");
        String age = request.getParameter("age");
        String scare = request.getParameter("scare");
        try {
            ServletContext servletContext = super.getServletContext();
            String configName = servletContext.getInitParameter("users");
            String path = servletContext.getRealPath("/" + configName);
            BufferedWriter bw = new BufferedWriter(new FileWriter(path, true));
            bw.write(username+","+age+","+scare);
            bw.newLine();
            bw.close();
            PrintWriter pw = response.getWriter();
            pw.print("succeed");
        } catch (IOException e) {
            PrintWriter pw = response.getWriter();
            pw.print("defeated");
            e.printStackTrace();
        }
    }

    @Override
    protected void doHead(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doHead(request, response);
    }
}
